package com.cjq.allservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjq.allservice.entity.Activity;
import com.cjq.allservice.entity.Address;
import com.cjq.allservice.entity.Swiper;
import com.cjq.allservice.entity.vo.ActivityQuery;
import com.cjq.allservice.entity.vo.SwiperQuery;
import com.cjq.allservice.service.ActivityService;
import com.cjq.utils.R;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cjq
 * @since 2022-01-11
 */
@RestController
@RequestMapping("/allservice/activity")
@CrossOrigin
public class ActivityController {

    @Autowired
    ActivityService activityService;

    @ApiOperation("用户发布组织活动添加")
    @PostMapping("/addActivity")
    public R addActivity(@RequestBody Activity activity,@RequestParam String fromDate,@RequestParam String toDate,@RequestParam String endDate){

        try {
            Date dateFrom = new SimpleDateFormat("yyyy-MM-dd").parse(fromDate);
            Date dateTo = new SimpleDateFormat("yyyy-MM-dd").parse(toDate);
            Date dateEnd = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
            activity.setActivityFrom(dateFrom);
            activity.setActivityTo(dateTo);
            activity.setActivityEnd(dateEnd);
            boolean save = activityService.save(activity);
            if (save!=true){
                return R.fail().message("添加失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.succ().message("添加成功！");


    }

    @ApiOperation("对组织活动进行删除取消")
    @DeleteMapping("/deleteActivity")
    public R deleteActivity(@RequestParam String id){
        boolean b = activityService.removeById(id);
        if (b==true){
            return R.succ().message("删除成功！");
        }else{
            return R.fail().message("删除失败！");
        }

    }



    @ApiOperation("根据用户的id获取本用户的组织活动列表")
    @GetMapping("/getActivityByUserId")
    public R getActivityByUserId(@RequestParam String userId){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("activity_user_id",userId);
        List<Activity> list = activityService.list(wrapper);
        return R.succ().data("activityList",list);
    }

    @ApiOperation("获取所有的组织活动")
    @GetMapping("/getAllActivity")
    public R getAllActivity(){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("activity_judge",1);
        List<Activity> list = activityService.list(wrapper);
        return R.succ().data("allActivityList",list);
    }


    @ApiOperation("管理员对组织活动进行审核")
    @PostMapping("/updateJudgeById")
    public R updateJudgeById(@RequestParam String id){
        Activity activity = activityService.getById(id);
        activity.setActivityJudge(1);
        boolean b = activityService.updateById(activity);
        if (b==true){
            return R.succ().message("审核成功！");
        }else {
            return R.fail().message("审核失败！");
        }
    }


    @ApiOperation("管理员对组织活动进行审核通过")
    @PostMapping("/updateJudge")
    public R updateJudge(@RequestBody Activity activity){
        activity.setActivityJudge(1);
        boolean b = activityService.updateById(activity);
        if (b==true){
            return R.succ().message("审核成功！");
        }else {
            return R.fail().message("审核失败！");
        }
    }

    @ApiOperation("管理员对组织活动进行审核不通过")
    @PostMapping("/updateNoJudge")
    public R updateNoJudge(@RequestBody Activity activity){
        activity.setActivityJudge(2);
        boolean b = activityService.updateById(activity);
        if (b==true){
            return R.succ().message("审核成功！");
        }else {
            return R.fail().message("审核失败！");
        }
    }

    @ApiOperation("管理员进行审核取消操作")
    @PostMapping("/updateNoWithJudge")
    public R updateNoWithJudge(@RequestBody Activity activity){
        activity.setActivityJudge(0);
        activity.setActivityJudgeContent(null);
        boolean b = activityService.updateById(activity);
        if (b==true){
            return R.succ().message("取消审核成功！");
        }else{
            return R.fail().message("取消审核失败！");
        }
    }



    @ApiOperation("根据id进行返回组织活动的具体信息")
    @GetMapping("/getActivityById")
    public R getActivityById(@RequestParam String activityId){
        Activity activity = activityService.getById(activityId);
        return R.succ().data("activityInfo",activity);
    }

    @ApiOperation("条件查询组织活动带分页")
    //条件查询带分页
    @PostMapping ("pageActivityCondition/{current}/{limit}")
    public R pageDoctorsCondition(@PathVariable long current, @PathVariable long limit, @RequestBody(required = false) ActivityQuery activityQuery){
        Page<Activity> page=new Page<>(current,limit);
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();

        //多条件组合查询
        String id = activityQuery.getActivityId();
        String name = activityQuery.getActivityText();
        String userId=activityQuery.getActivityUserId();
        if (!StringUtils.isEmpty(id)){
            wrapper.like("activity_id",id);
        }
        if (!StringUtils.isEmpty(name)){
            wrapper.like("activity_text",name);
        }
        if (!StringUtils.isEmpty(userId)){
            wrapper.like("activity_user_id",userId);
        }
        wrapper.orderByDesc("update_time");

        activityService.page(page,wrapper);
        long total=page.getTotal();
        System.out.println(total);
        List<Activity> records = page.getRecords();
        HashMap map = new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return R.succ().data(map);
    }



    @ApiOperation("将所有组织活动的信息导出到excel文件")
    @GetMapping("/exportActivitysInfo")
    public void exportDoctorsInfo(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String date= dateFormat.format(new Date()).toString();
        HSSFSheet sheet = workbook.createSheet(date + "allActivitys");

        final List<Activity> allActivitys; //要导出的数据
        allActivitys= activityService.list();

        // 设置要导出的文件的名字
        String fileName = "AllActivity" + ".xls";

        // 新增数据行，并且设置单元格数据
        int rowNum = 1;

        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = {"序号","ID","标题", "活动信息","人数","审核状态","创建人ID","开始时间","结束时间","创建时间","管理员审核意见"};
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Activity activity : allActivitys) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(rowNum);
            row1.createCell(1).setCellValue(activity.getActivityId());
            row1.createCell(2).setCellValue(activity.getActivityText());
            row1.createCell(3).setCellValue(activity.getActivityInfo());
            row1.createCell(4).setCellValue(activity.getActivityNumber());
            if (activity.getActivityJudge()==0){
                row1.createCell(5).setCellValue("未审核");
            }else if(activity.getActivityJudge()==1) {
                row1.createCell(5).setCellValue("审核成功");
            }else{
                row1.createCell(5).setCellValue("审核失败");
            }
            row1.createCell(6).setCellValue(activity.getActivityUserId());

            row1.createCell(7).setCellValue(activity.getActivityFrom());
            row1.createCell(8).setCellValue(activity.getActivityTo());
            row1.createCell(9).setCellValue(activity.getCreateTime());
            row1.createCell(10).setCellValue(activity.getActivityJudgeContent());

            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
}

